<template>
  <div class="app-container">
    <uc-table url="admin/user/getUserPage" name="用户" ref="userTable" pageable table-border :search-form="searchForm"
              @selection-change="handleSelectionChange">
      <template slot="searchForm">
        <el-form size="mini" :inline="true" :model="searchForm" class="demo-form-inline filter-container">
          <!--搜索输入框-->
          <el-form-item>
            <el-input type="text" v-model="searchForm.name" placeholder="请输入姓名" clearable
                      @clear="clearInput()"></el-input>
          </el-form-item>
          <el-form-item v-if="enterPriseHidden">
            <el-select v-model="searchForm.flagId" placeholder="请选择主体" style="width: 100%" clearable
                       @clear="clearInput1()">
              <el-option v-for="(item,index) in enterpriseDominantList" :key="index" :value="item.ucId"
                         :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.online" placeholder="请选择在线状态" style="width: 100%" clearable>
              <el-option :value=1 label="在线"></el-option>
              <el-option :value=0 label="离线"></el-option>
            </el-select>
          </el-form-item>
          <!--搜索按钮--新增按钮-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch()">查询</el-button>
            <el-button type="success" icon="el-icon-plus" class="filter-item" @click="handleAdd()">新 增</el-button>
            <el-button type="info" plain icon="el-icon-upload" class="filter-item" @click="handleImport()">导 入
            </el-button>
            <el-button type="warning" plain icon="el-icon-download" class="filter-item" @click="handleExport()">导 出
            </el-button>
            <el-button type="primary" plain icon="el-icon-setting" class="filter-item" @click="handleSetting()">审 核
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <template slot="columns">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="userName" label="用户名" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="name" label="姓名" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="roleId" label="所属角色" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{roleFormat(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseDominantName" label="所属主体" align="left"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="mobile" label="电话" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sex" label="性别" align="left">
          <template slot-scope="scope">
            {{ scope.row.sex | formDateSex }}
          </template>
        </el-table-column>
        <el-table-column label="在线状态" prop="online">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.online === 1 ? 'success' : 'info'"
                disable-transitions>{{scope.row.online === 1 ? '在线' : '离线'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户状态" prop="status">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="点击切换用户可用状态" placement="top">
              <el-tag class="pointer" @click="handleChangStatus(scope.row)" :type="scope.row.status?'success':'danger'">
                {{ scope.row.status ? "可用" : "禁用" }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="checkStatus">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" placement="top">
              <el-tag class="pointer" :type="scope.row.checkStatus==1?'success':'danger'">
                {{ scope.row.checkStatus == 1 ? "可用" : "未审核" }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="220" align="left" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!--编辑按钮-->
            <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" icon="el-icon-info" type="success" @click="handleInfo(scope.row)">详情</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" :loading="deleteLoading"
                       @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </uc-table>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--          <el-checkbox v-model="upload.updateSupport"/>-->
          <!--          是否更新已经存在的用户数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅支持批量导入便名警务站用户!仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="用户审核" :visible.sync="checkOpen" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="(item,index) in roleList" :key="index" :value="item.ucId"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="所属岗位" prop="postCodeList">-->
<!--          <el-select v-model="form.postCodeList" multiple placeholder="请选择岗位" style="width: 100%">-->
<!--            <el-option v-for="(item,index) in postList" :key="index" :value="item.postCode"-->
<!--                       :label="item.postName"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import UcTable from "@/components/UcTable/index.vue";
import {deleteInUser, updateInUser, getInEnterpriseList, exportInUser} from "@/api/enterprise";
import {getInEnterpriseDominantList} from "@/api/enterpriseDominant";
import {export2Excel} from "@/utils";
import {getToken} from "@/utils/auth";
import {getInRoleList} from "@/api/role";
import {getPostList} from "@/api/post";

export default {
  name: "userList",
  components: {UcTable},
  data() {
    return {
      searchForm: {
        deleted: false,
        online:null
      },
      deleteLoading: false,
      enterpriseDominantList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: getToken()},
        // 上传的地址process.env.VUE_APP_BASE_API
        url: '/api/admin/user/importInUser'
      },
      ids: [],
      form: {
        roleId: "",
        postCodeList: []
      },
      checkOpen: false,
      rules: {
        roleId: [{required: true, message: '角色不能为空', trigger: "blur"}],
        // postCodeList: [{required: true, message: '岗位不能为空', trigger: "blur"}]
      },
      roleList: [],
      //选中岗位编码数组
      postCodeList: [],
      //岗位列表
      postList: []
    }
  },
  computed: {
    enterPriseHidden() {
      let roleCode = this.$store.getters.roleCode;
      return roleCode == "ADMIN" || roleCode == "XT-ADMIN" || roleCode == "ZD-ADMIN" || roleCode == "DD-ADMIN" || roleCode == "JW-ADMIN"
    }
  },
  created() {
    if(this.$route.params.online){
      this.searchForm.online=this.$route.params.online
    }
    this.getInEnterpriseDominantList()
    this.getInRoleList()
    this.getPostList()
  },
  methods: {
    roleFormat(row){
      let result;
      this.roleList.forEach(r=>{
        if(r.ucId===row.roleId){
          result = r.name
          return r.name
        }
      })
      return result
    },
    getPostList() {
      getPostList({}).then(res => {
        this.postList = res.data
      })
    },
    getInRoleList() {
      getInRoleList({}).then(res => {
        this.roleList = res.data
      })
    },
    //审核按钮
    handleSetting() {
      if (this.ids.length < 1) {
        return this.$message({
          message: "请选择要审核的用户！",
          type: 'warning'
        });
      }
      this.form = this.$options.data().form
      this.checkOpen = true
    },
    //提交审核
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const customize = " and id in (" + this.ids.join(",") + ") "
          const data = {
            customize: customize,
            roleId: this.form.roleId,
            postCode: this.form.postCodeList.join(","),
            checkStatus: 1,
            status: true
          }
          updateInUser(data).then(res => {
            this.$notify.success({
              title: '成功',
              message: "审核成功"
            })
            this.handleSearch()
            this.checkOpen = false
          }).catch(res => {
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          })
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
      this.handleSearch()
    },
    /** 导出模板*/
    importTemplate() {
      let columns = [{title: '用户名', key: 'userName'}, {title: '姓名', key: 'name'}
        , {title: '可登录权限', key: 'typeName'}, {title: '联系电话', key: 'mobile'}, {
          title: '详细地址',
          key: 'address'
        }, {title: '性别', key: 'sexName'}]
      let list = [{
        "userName": "zhangsan",
        "name": "张三",
        "typeName": "app/pc/全部",
        "mobile": "15299688492",
        "address": "地址",
        "sexName": "男/女"
      }]
      //   , {title: '可登录权限', key: 'type'}, {title: '联系电话', key: 'mobile'}, {title: '详细地址', key: 'address'}]
      export2Excel(columns, list, '用户信息')
    },
    /** 导出*/
    handleExport() {
      let columns = [{title: '姓名', key: 'name'}, {title: '用户名', key: 'userName'}
        , {title: '所属主体', key: 'enterpriseDominantName'}, {title: '电话', key: 'mobile'}, {
          title: '地址',
          key: 'address'
        }, {title: '性别', key: 'sexName'}]
      export2Excel(columns, Object.assign([], this.$refs.userTable.data), '用户信息')
      // exportInUser(this.searchForm).then(res=>{
      //   this.exportExcelStream(res)
      // })
    },
    handleSearch() {
      this.$refs.userTable.getTableData(1)
    },
    handleAdd() {
      this.$router.push("/sys/useredit/0")
    },
    handleEdit(val) {
      this.$router.push("/sys/useredit/" + val.ucId)
    },
    handleInfo(val) {
      this.$router.push("/sys/userinfo/" + val.ucId)
    },
    clearInput() {
      //清除输入框
      this.searchForm.name = null
      this.handleSearch()
    },
    clearInput1() {
      //清除输入框
      this.searchForm.flagId = null
      this.handleSearch()
    },
    //变更用户可用状态
    handleChangStatus(val) {
      this.$confirm('您确定要执行变更' + val.name + '这个用户状态吗？', '提醒信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let obj = Object.assign({}, val)
        obj.status = !obj.status
        updateInUser(obj).then(res => {
          this.$notify.success({
            title: '成功',
            message: "变更角色状态成功"
          })
          this.handleSearch()
        }).catch(res => {
          this.$notify.error({
            title: '失败',
            message: res.msg
          })
        })
      })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消变更角色状态'
            });
          });
    },
    handleDelete(val) {
      this.$confirm('您确定要执行删除' + val.userName + '这个用户吗？', '提醒信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteLoading = true
        deleteInUser(val).then(res => {
          this.deleteLoading = false
          this.$notify.success({
            title: '成功',
            message: "删除用户成功"
          })
          this.handleSearch()
        }).catch(res => {
          this.deleteLoading = false
          this.$notify.error({
            title: '失败',
            message: res.msg
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getInEnterpriseDominantList() {
      getInEnterpriseDominantList({deleted: false}).then(res => {
        this.enterpriseDominantList = res.data
      }).catch(error => {

      })
    }
  }
}
</script>

<style scoped>

</style>
